<?php
$xpath_agent = "/home/luanjunyi/yhhd/py/taras/tools/xpath_agent ";
$taras_server_addr = 'http://192.168.1.116:1988/xpath';

ini_set('display_errors',1);
error_reporting(E_ALL);

set_error_handler('handle_error');

function handle_error($errno, $error_message, $error_file, $error_line) {
  echo "<b>Error: ({$error_file}:{$error_line}:{$error_message})</b>";
  die('<br/><br/>Good luck debugging');
}

require_once('sites-func/db.php');
require_once '../util.php';
require_once '../config.php';

connect_db();

// Update database
if(isset($_GET['op'])) {

    if($_GET['op'] == 'delete_item') {
      
      $succ = mysql_query('delete from source_item where id = \''.$_POST['item_id'].'\'');
      if (!$succ) {
        echo 'failed: ' . mysql_error();
      } else {
        echo '条目已删除: ' . $_POST['item_id'];
      }
      return;

    } else if($_GET['op'] == 'add_item') { 
      add_source_item($_POST);
      return;
      
    } else if($_GET['op'] == 'update_item') {

      $sql = sprintf('update source_item set title_xpath = "%s", content_xpath = "%s", image_xpath = "%s", href_xpath = "%s" where id = %d ',
                     $_POST['title_xpath'], $_POST['content_xpath'], $_POST['image_xpath'], $_POST['href_xpath'],
                     $_POST['item_id']);
      $ret = mysql_query($sql);
      if (!$ret) {
        echo "failed: " . mysql_error();
      } else {
        echo mysql_affected_rows() . ' rows updated';
      }
      return;
    } else if($_GET['op'] == 'test_item') {

      if(isset($_POST['keyword']) and $_POST['keyword']) {
        $_POST['url'] = $_POST['url'] . urlencode(iconv('UTF-8', $_POST['encoding'] ,$_POST['keyword']));
      }

      chdir('tmp');

      $check_cmd = sprintf($xpath_agent . "-u '%s' -t '%s' -a '%s' -i '%s' -c '%s' 2> stderr",
                           $_POST['url'],
                           str_replace("'",'"',$_POST['title_xpath']),
                           str_replace("'",'"',$_POST['href_xpath']),
                           str_replace("'",'"',$_POST['image_xpath']),
                           str_replace("'",'"',$_POST['content_xpath']));

      exec($check_cmd, $check_result);

      $img_path = '';
      if (strlen($check_result[1]) > 0) {
        $img_path = 'tmp/' . $check_result[1];
      }
      $check_result = array('tweet' => $check_result[0], 'image' => $img_path);
      echo json_encode($check_result);
      return;

    } else if($_GET['op'] == 'delete_source') {
      echo json_encode(remove_source($_POST['source_id']));
      return;

    } else if($_GET['op'] == 'edit') {  // edit source info
      if (edit_source($_POST) == -1) { // from sites-func/db.php
        // Fatal error from edit_source()
        return;
      }

    } else if($_GET['op'] == 'add') { // add source
      if (add_source($_POST) == -1) { // from sites-func/db.php
        // Fatal error from add_source()
        return;
      }
      header('Location: '.$_SERVER['HTTP_REFERER']);
    }
    return;
} 
?>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="/lib/js/jquery.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.form.js"></script>
    <script type="text/javascript" src="/lib/js/sprintf.js"></script>
    <link rel="stylesheet" type="text/css" href="/lib/css/reset.css" />
    <link rel="stylesheet" type="text/css" href="css/redips-dialog.css" />
    <link rel="stylesheet" type="text/css" href="css/sites.css" />
    <script type="text/javascript" src="js/redips-dialog.js"></script>
    <script type="text/javascript" src="js/jquery.jstree.js"></script>
    <script type="text/javascript" src="js/sites.js"></script>


    <title>Taras管理后台 | 微博改变生活 | 北京友好互动科技发展有限公司</title>
  </head>
  <body>

<div id="add_source_template" style="display:none" >
  <?php include 'sites-module/item-detail.php'; ?>  
</div>

<div class="add_source">
  <table><tr>
      <!--keyword tree goes here-->
      <td width="25%" valign="top">
        <div id="kw_tree"></div>
      </td>

      <td width="75%" valign="top">

        <?php 
           $sm_type="add";
           include "sites-module/source-manage.php";
           unset($sm_type);
           ?>
      </td>
  </tr>
  <tr>
    <td width="25%"></td>
    <td width="75%">
      <form id="select-source-div" method="GET" action="index.php">
        URL： <input type="text" name="search-url" size="26" value="" />
        标签： <input type="text" name="search-tag" size="10" value="" />
        <input type="submit" value="查找" />
        <a href="index.php" style="margin-left: 20px; display: inline-block;">显示最新</a>
      </form>
    </td>
  </tr>
  </table>

</div>

<?php
  // show sources
  if (isset($_GET['search-url']) && strlen($_GET['search-url']) > 0) {
    $sql = sprintf("select id from source where base_url like '%%%s%%'",
                   $_GET['search-url']);

    $result_limit = 0;

  } else if (isset($_GET['search-tag']) && strlen($_GET['search-tag']) > 0) {
    $tag = str_replace('|', '\\\\|', $_GET['search-tag']);

    $regex = sprintfn("'^%(tag)s#|#%(tag)s#|#%(tag)s$|^%(tag)s$'",
                      array('tag' => $tag));

    $sql = sprintf("select id from source where tags regexp %s",
                   $regex);
    $result_limit = 0;

  } else {
    $sql = 'select id from source';
    $result_limit = 10;
  }

  $ret = mysql_query($sql);
  
  $all_rows = array();
  while ($row = mysql_fetch_assoc($ret)) {
    $all_rows[] = $row;
  }
  uasort($all_rows, 'cmp_row');

  if ($result_limit > 0) {
    $all_rows = array_slice($all_rows, 0, $result_limit);
  }

  $count = 0;
  foreach ($all_rows as $result) {
    ++$count;
?>
<div class="listing">
<table><tr>
<!--keyword tree-->
<td width="25%" valign="top">
  <div class="kw_tree"></div>
</td>
<!--source info-->
<td width="75%" valign="top">
  <div class = "exist-source  <?php echo $count % 2 == 0 ? 'even-div': 'odd-div'?>" >
   <?php
      $sm_type = "edit";
      $source_id = $result['id'];
      include 'sites-module/source-manage.php';
   ?>
  </div>
</td>
</tr></table>
</div>



<?php
  }
?>

</body>
</html>
